package com.lzh.chatnote.common.service;

import com.lzh.chatnote.common.exception.BusinessErrorEnum;
import com.lzh.chatnote.common.exception.BusinessException;
import lombok.SneakyThrows;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;

@Component
public class RedisService {

    @Resource
    private RedissonClient redissonClient;

    public <T> T executeWithLock(String key, int waitTime, TimeUnit unit, SupplierThrow<T> supplier) throws Throwable{
        RLock lock = redissonClient.getLock(key);
        boolean tryRes = lock.tryLock(waitTime, unit);
        if(!tryRes){
            throw new BusinessException(BusinessErrorEnum.REQUEST_TOO_FREQUENTLY);
        }
        try {
           return supplier.get();
        }finally {
            lock.unlock();
        }
    }

    @SneakyThrows
    public <T> void executeWithLock(String key, Runnable runnable){
        RLock lock = redissonClient.getLock(key);
        boolean tryRes = lock.tryLock();
        if(!tryRes){
            throw new BusinessException(BusinessErrorEnum.REQUEST_TOO_FREQUENTLY);
        }
        try {
            runnable.run();
        }finally {
            lock.unlock();
        }
    }

    @FunctionalInterface
    public interface SupplierThrow<T> {

        /**
         * Gets a result.
         *
         * @return a result
         */
        T get() throws Throwable;
    }

}
